import { Component, OnInit } from '@angular/core';
import {PageSubject} from '../../../util/page-subject';
import {DataDictionaryService} from '../../../services/dataDictionary.service';
import {ResponseUtil} from '../../../util/response-util';
import {MsgConstants} from '../../../constants/constants';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {DataAuditGeneratedService} from './data-audit-generated.service';

declare var moment;

@Component({
  selector: 'app-data-audit-generated',
  templateUrl: './data-audit-generated.component.html',
  styleUrls: ['./data-audit-generated.component.css']
})
export class DataAuditGeneratedComponent implements OnInit {

  dicCode = 'SJSC';
  dataTypeArr: Array<any> = [];
  factorType: string;

  startDate = new Date();
  endDate = new Date();

  isLoading = false;

  timeDataType = 'dayData';
  timeDataName = '日';
  timeDataFormat = 'YYYY-MM-DD 00:00:00';
  timeDataArr: Array<any> = [];

  constructor(
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private dialogService: OneDialogService,
    private dicService: DataDictionaryService,
    private generatedService: DataAuditGeneratedService
  ) { }

  ngOnInit() {
    this.pushPage();
    this.initData();
    this.getDicData();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    // const path = new Path('数据校正', '');
    this.pageSubject.pushPage('生成数据', '');
  }

  /**
   * 初始化数据
   */
  initData () {
    this.timeDataArr = [
      {'name': '日', dataType: 'dayData', formatter: 'YYYY-MM-DD', mode: 'day', format: 'YYYY-MM-DD 00:00:00'},
      {'name': '周', dataType: 'weekData', formatter: 'YYYY-MM-DD', mode: 'day', format: 'YYYY-MM-DD 00:00:00'},
      {'name': '月', dataType: 'monthData', formatter: 'YYYY-MM', mode: 'month', format: 'YYYY-MM-XX 00:00:00'},
      {'name': '年', dataType: 'yearData', formatter: 'YYYY', mode: 'month', format: 'YYYY-AA-BB 00:00:00'}
    ];
  }

  /**
   * 获取数据生成的字典数据
   */
  getDicData = () => {
    this.dicService.getChildDicByCode(this.dicCode).subscribe(
      result => this.responseUtil.success(result, this.processDiceResult),
      error => this.responseUtil.error(error)
    )
  };
  processDiceResult = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data.length > 0) {
        this.dataTypeArr = result.data;
        this.factorType = this.dataTypeArr[0].value
      }
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 获取数据生成的字典数据
   */
  getDataGenerated = () => {
    this.isLoading = true;
    let startFormat = this.timeDataFormat.replace(/-/g, '/');
    if (startFormat.indexOf('XX') !== -1) {
      startFormat = startFormat.replace('XX', '01');
    }
    if (startFormat.indexOf('AA/BB') !== -1) {
      startFormat = startFormat.replace('AA/BB', '01/01');
    }
    const startDate = this.startDate ? moment(this.startDate).format(startFormat) : '';
    const endDate = this.endDate ? moment(this.endDate).format(startFormat) : '';
    let dataObj = {
      monitorTime: startDate.replace(/\//g, '-'),
      dataType: this.timeDataType,
      factorType: this.factorType
    };
    if (this.timeDataType === 'dayData') {
      const timeObj = {
        startDate:  startDate.replace(/\//g, '-'),
        endDate: endDate.replace(/\//g, '-')
      };
      dataObj = Object.assign(dataObj, timeObj);
    }
    this.generatedService.getDataGenerated(dataObj).subscribe(
      result => this.responseUtil.success(result, this.processGenerated),
      error => this.responseUtil.error(error, () => {
        this.isLoading = false;
      })
    )
  };
  processGenerated  = (result) => {
    this.isLoading = false;
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      this.dialogService.success('数据生成功')
    }
    if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };

  /**
   * 时间类型切换
   * @param timeData
   */
  timeDataChange(timeData) {
    if (this.timeDataType !== timeData.dataType) {
      this.timeDataType = timeData.dataType;
      this.timeDataName = timeData.name;
      this.timeDataFormat = timeData.format;
      if (timeData.dataType === 'weekData') {
        let startDate = this.startDate;
        startDate = new Date(moment(startDate).day(-7).format(timeData.formatter.replace(/-/g, '/')));
        startDate = new Date(moment(startDate).day(7).format(timeData.formatter.replace(/-/g, '/')));
        this.startDate = startDate;
      }
    }
  }
  /**
   * 时间类型切换
   * @param isOpen
   */
  timeTypeChange(isOpen) {
    if (!isOpen) {
      let timeData;
      this.timeDataArr.filter((val) => {
        if (val.dataType === this.timeDataType) {
          timeData = val;
        } else {
          return true;
        }
      });
      this.timeDataName = timeData.name;
      this.timeDataFormat = timeData.format;
      if (timeData.dataType === 'weekData') {
        let startDate = this.startDate;
        startDate = new Date(moment(startDate).day(-7).format(timeData.formatter.replace(/-/g, '/')));
        startDate = new Date(moment(startDate).day(7).format(timeData.formatter.replace(/-/g, '/')));
        this.startDate = startDate;
      }
    }
  }
  /**
   * 开始时间、结束时间
   */
  disabledStartDate = (startValue) => {
    if (!startValue) {
      return false;
    }
    if (this.timeDataType === 'weekData') {
      return startValue.getDay() !== 0 || startValue.getTime() > new Date().getTime();
    } else {
      return startValue.getTime() > new Date().getTime();
    }
  };
  disabledEndDate = (endValue) => {
    if (!endValue || !this.startDate) {
      return false;
    }
    const startTime = new Date(moment(this.startDate).format('YYYY/MM/DD 00:00:00'));
    const endTime = new Date(moment(endValue).format('YYYY/MM/DD 23:59:59'));
    const nowTime = new Date(moment().format('YYYY/MM/DD 23:59:59'));
    return endTime.getTime() < startTime.getTime() || endTime.getTime() > nowTime.getTime();
  };
  get timeFormatter() {
    let formatter = 'YYYY-MM-DD';
    this.timeDataArr.every( (val) => {
      if (val.dataType === this.timeDataType) {
        formatter = val.formatter;
      } else {
        return true;
      }
    });
    return formatter;
  }
  get timeMode() {
    let dataMode = 'day';
    this.timeDataArr.every( (val) => {
      if (val.dataType === this.timeDataType) {
        dataMode = val.mode;
      } else {
        return true;
      }
    });
    return dataMode;
  }
}
